<template>
  <div class="echarts-container">
    <el-card shadow="hover" class="rounded-lg overflow-hidden card">
      <div class="flex space-x-2">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="时间范围">
            <el-date-picker
             v-model="timeFrame"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :clearable="true"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="机台类型">
            <el-select
              size="small"
              v-model="typeMTTRCode"
              placeholder="请选择机台类型"
              multiple
              @change="handleTypeChange"
              @visible-change="getTypeCodeOptions"
            >
              <el-option value="" label="整体"></el-option>
              <el-option
                v-for="item in typeCodeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="onMTTRSubmit"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-input
              size="small"
              style="width: 100%"
              placeholder="设置设备MTTR标准"
              v-model="MTTRStandard"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="onMTTRStandard">
              确定
            </el-button>
            <el-button size="small" @click="onMTTRReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card shadow="hover" class="rounded-lg overflow-hidden card">
      <div
        class="flex justify-between items-center mb-4 px-4 pt-2"
        style="margin-bottom: 20px"
      >
        <div
          v-if="confirmTypeMTTRLabels.length > 0"
          style="margin-bottom: 10px"
        >
          <span class="tag-group__title">已选择:</span>
          <el-tag
            v-for="(item, index) in confirmTypeMTTRLabels"
            :key="index"
            type="success"
            effect="dark"
            style="margin-right: 2px"
          >
            {{ item }}
          </el-tag>
        </div>
        <div class="flex space-x-2">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-refresh"
            @click="refreshMTTRChart(1)"
          >
            刷新
          </el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-zoom-in"
            @click="MTTRZoomIn"
          >
            放大
          </el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-zoom-out"
            @click="MTTRZoomOut"
          >
            缩小
          </el-button>
        </div>
      </div>
      <!-- 折线图组件 -->
      <div ref="MTTRRef" class="w-full h-[400px]"></div>
      <div class="px-4 py-2 text-sm text-gray-500">
        <p>
          数据说明：MTTR（平均修复时间）的作用是衡量系统或设备的维修效率，数值越低表示故障处理速度越快，可用性越高。
        </p>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import { debounce } from "lodash-es";
import { getToken } from "@/utils/auth";

export default {
  name: "equipmentWeeklyReport",
  data() {
    return {
      timeFrame: "", //时间范围
      typeMTTRCode: [], //机台类型
      typeMTTRLabels: [], //选择的机台
      confirmTypeMTTRLabels: [],
      MTTRStandard: "", //MTTR标准
      typeCodeOptions: [],
      // MTTR表
      MTTRChart: null,
      MTTRChartOption: {
        backgroundColor: "rgba(255, 255, 255, 0.9)",
        title: {
          text: "整体设备MTTR趋势分析",
          left: "center",
          textStyle: {
            color: "#333",
            fontWeight: "normal",
            fontSize: 16,
          },
        },
        tooltip: {
          trigger: "axis",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: { color: "#333" },
          padding: 10,
          extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);",
          formatter: (params) => {
            let result = `<div class="font-semibold">${params[0].name}</div>`;
            params.forEach((item) => {
              const color = item.color;
              const value = item.value;
              const name = item.seriesName;
              result += `
                <div class="flex items-center mt-1">
                  <span class="inline-block w-3 h-3 rounded-full mr-2" style="background-color: ${color}"></span>
                  <span class="mr-2">${name}:</span>
                  <span class="font-semibold">${value} 分钟</span>
                </div>
              `;
              if (
                value !== this.MTTRChartOption.series[0].markLine.data[0].yAxis
              ) {
                const deviation =
                  value - this.MTTRChartOption.series[0].markLine.data[0].yAxis;
                const deviationText =
                  deviation > 0
                    ? `<span class="text-green-500">+${deviation} 分钟 (优于标准)</span>`
                    : `<span class="text-red-500">${deviation} 分钟 (低于标准)</span>`;
                result += `
                  <div class="ml-5 text-xs mt-0.5">
                    <span class="text-gray-500">与标准差值:</span> ${deviationText}
                  </div>
                `;
              }
            });
             // 展示topTypes
             if (this.topTypes && Array.isArray(this.topTypes)) {
              // 找到当前x轴时间对应的topTypes
              const timeTopTypes = this.topTypes.find(
                function(arr) { return arr.length > 0 && arr[0].time === params[0].name; }
              );
              if (timeTopTypes && timeTopTypes.length > 0) {
                result += `<div style="margin-top:8px;"><b>本期TOP5类型：</b></div>`;
                timeTopTypes.forEach(function(typeItem) {
                  result += `
                    <div>
                      <span>${typeItem.type}：</span>
                      <span>${typeItem.count}台</span>
                      <span style="margin-left:8px;">${typeItem.percent}%</span>
                    </div>
                  `;
                });
              }
            }
            // 展示topEquipments
            if (this.topEquipments && Array.isArray(this.topEquipments) && this.topEquipments.length > 0) {
              result += `<div style="margin-top:8px;"><b>本期TOP5设备：</b></div>`;
              this.topEquipments.forEach(function(eqItem) {
                result += `
                  <div>
                    <span>${eqItem.equipmentId}：</span>
                    <span>${eqItem.count}台</span>
                    <span style="margin-left:8px;">${eqItem.percent}%</span>
                  </div>
                `;
              });
            }
            return result;
          },
        },
        legend: {
          type: "scroll",
          orient: "horizontal",
          bottom: "5%",
          left: "center",
          pageButtonItemGap: 5,
          pageButtonColor: "#666",
          pageButtonActiveColor: "#409EFF",
          data: ["设备MTTR标准"],
        },
        grid: {
          left: "5%",
          right: "5%",
          bottom: "15%",
          top: "10%",
          containLabel: true,
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
              name: "设备MTTR趋势图",
              title: "保存为图片",
              type: "png",
              backgroundColor: "white",
            },
            dataView: {
              title: "数据视图",
              readOnly: true,
              buttonColor: "#409EFF",
              buttonTextStyle: { color: "#fff" },
            },
          },
          right: "5%",
          top: "2%",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [],
          axisLine: {
            lineStyle: {
              color: "#999",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            interval: 0,
            rotate: 0,
            color: "#666",
            // formatter: function (value) {
            //   if (value.includes('W')) {
            //     return value.replace('W', '周 ');
            //   }
            //   return value;
            // }
          },
        },
        yAxis: {
          type: "value",
          name: "分钟",
          nameLocation: "middle",
          nameGap: 50,
          min: 0.0,
          splitNumber: 5,
          axisLine: {
            lineStyle: {
              color: "#999",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "#666",
            formatter: function (value) {
              return value + "min";
            },
          },
          splitLine: {
            lineStyle: {
              color: "#eee",
            },
          },
        },
        series: [
          {
            name: "设备MTTR标准",
            type: "line",
            markLine: {
              silent: true,
              symbol: "none",
              label: {
                show: true,
                position: "end",
                formatter: "{c}",
              },
              lineStyle: {
                type: "dashed",
                color: "#67c23a",
                width: 2,
                shadowBlur: 5,
                shadowColor: "rgba(103, 194, 58, 0.3)",
              },
              data: [
                {
                  yAxis: 0, // 这里设置参考线的值
                },
              ],
            },
          },
          // {
          //   name: '趋势变化',
          //   type: 'bar',
          //   data: [null, 5, 10, 10, 5, 75, -105],
          //   barWidth: 8,
          //   itemStyle: {
          //     color: function(params) {
          //       return params.value >= 0 ? '#67c23a' : '#f56c6c';
          //     }
          //   },
          //   label: {
          //     show: true,
          //     position: 'top',
          //     formatter: function(params) {
          //       if (params.value > 0) return '+' + params.value;
          //       if (params.value < 0) return params.value;
          //       return '';
          //     },
          //     color: function(params) {
          //       return params.value >= 0 ? '#67c23a' : '#f56c6c';
          //     }
          //   }
          // }
        ],
      },
      MTTRChartZoom: 1,
    };
  },
  mounted() {
    this.initMTTRChart();
    // 初始化放大
    this.MTTRZoomIn();
    // 使用防抖处理窗口大小变化，避免频繁重绘
    this.resizeHandler = debounce(() => {
      this.resizeChart();
    }, 100);
    window.addEventListener("resize", this.resizeHandler);
  },

  beforeDestroy() {
    if (this.MTTRChart) {
      this.MTTRChart.dispose();
      this.MTTRChart = null;
    }
    window.removeEventListener("resize", this.resizeHandler);
  },
  methods: {
    // 获取下拉菜单
    async getTypeCodeOptions() {
      const token = getToken();
      const params = {};
      const response = await axios.get(
        `${process.env.VUE_APP_BASE_API}/wareHouses/equipmentId`,
        {
          params,
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );
      this.typeCodeOptions = response.data;
    },
    // 选择
    handleTypeChange(values) {
      // 清空之前的label
      this.typeMTTRLabels = [];
      // 查找每个选中值对应的label
      values.forEach((value) => {
        // 处理特殊情况：值为空字符串对应"整体"
        if (value === "") {
          this.typeMTTRLabels.push("整体");
          return;
        }

        // 从选项列表中查找对应的label
        const option = this.typeCodeOptions.find(
          (item) => item.value === value
        );
        if (option) {
          this.typeMTTRLabels.push(option.label + "(" + value + ")");
        }
      });
    },
    // 获取折线图数据
    async getMTTRChartOption(value) {
      const token = getToken();
      let equipmentIds = [];
      let startDate = "";
      let endDate = "";
      if (this.timeFrame) {
        startDate = this.timeFrame[0];
        endDate = this.timeFrame[1];
      }
      if (value) {
        equipmentIds = value;
      }
      try {
        const response = await axios.post(
          "/dev-api/wareHouses/MTTR",
          equipmentIds,
          {
            params: {
              startDate,
              endDate,
            },
            headers: {
              Authorization: `Bearer ${token}`,
            },
            responseType: "json",
          }
        );
        this.MTTRChartOption.xAxis.data = response.data.xAxis;
        this.createPolyline(response.data.series);
        // 新增：赋值topTypes和topEquipments
        this.topTypes = response.data.topTypes || [];
        this.topEquipments = response.data.topEquipments || [];
      } catch (error) {
        console.error("Error:", error);
        throw error;
      }
    },
    // 创建处理折线数据
    createPolyline(series) {
      this.MTTRChartOption.series.splice(1);
      this.MTTRChartOption.legend.data.splice(1);
      series.forEach((seriesData, index) => {
        // 创建随机颜色
        const baseColor = this.getRandomColor();

        const seriesItem = {
          name: seriesData.name,
          type: "line",
          data: seriesData.data,
          smooth: true,
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
          itemStyle: {
            color: baseColor,
            borderWidth: 2,
            borderColor: "#fff",
            shadowBlur: 10,
            shadowColor: "rgba(0, 0, 0, 0.2)",
          },
          lineStyle: {
            width: 3,
            color: this.getGradientColor(baseColor),
          },
          shadowBlur: 10,
          shadowColor: "rgba(64, 158, 255, 0.3)",
        };

        // 添加到系列数组
        this.MTTRChartOption.series.push(seriesItem);
        this.MTTRChartOption.legend.data.push(seriesData.name);
      });
    },
    // 生成随机颜色
    getRandomColor() {
      const letters = "0123456789ABCDEF";
      let color = "#";
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
    // 生成渐变颜色
    getGradientColor(baseColor) {
      return {
        type: "linear",
        x: 0,
        y: 0,
        x2: 1,
        y2: 0,
        colorStops: [
          { offset: 0, color: baseColor },
          { offset: 1, color: this.lightenColor(baseColor, 0.5) },
        ],
      };
    },
    // 变亮颜色
    lightenColor(color, percent) {
      var R = parseInt(color.substring(1, 3), 16);
      var G = parseInt(color.substring(3, 5), 16);
      var B = parseInt(color.substring(5, 7), 16);

      R = parseInt((R * (100 + percent)) / 100);
      G = parseInt((G * (100 + percent)) / 100);
      B = parseInt((B * (100 + percent)) / 100);

      R = R < 255 ? R : 255;
      G = G < 255 ? G : 255;
      B = B < 255 ? B : 255;

      var RR =
        R.toString(16).length == 1 ? "0" + R.toString(16) : R.toString(16);
      var GG =
        G.toString(16).length == 1 ? "0" + G.toString(16) : G.toString(16);
      var BB =
        B.toString(16).length == 1 ? "0" + B.toString(16) : B.toString(16);

      return "#" + RR + GG + BB;
    },
    // 初始化折线图
    async initMTTRChart(value) {
      await this.getMTTRChartOption(value);
      const chartDom = this.$refs.MTTRRef;
      this.MTTRChart = echarts.init(chartDom);

      // 设置图表配置项
      if (this.MTTRChartOption) {
        this.MTTRChart.setOption(this.MTTRChartOption);
      }

      // 添加图表事件监听
      this.MTTRChart.on("click", (params) => {
        if (params.componentType === "series") {
          this.$message({
            message: `您点击了 ${params.name} 的 ${params.seriesName}: ${params.value} 分钟`,
            type: "info",
          });
        }
      });
    },

    resizeChart() {
      if (this.MTTRChart) {
        this.MTTRChart.resize();
      }
    },

    // 刷新
    async refreshMTTRChart(value) {
      if (value == 1) {
        await this.getMTTRChartOption(null);
        this.confirmTypeMTTRLabels = [];
      }
      this.onMTTRReset();
      if (this.MTTRChart) {
        this.MTTRChart.setOption(this.MTTRChartOption, true);
        this.$message({
          message: "图表数据已刷新",
          type: "success",
        });
      }
    },
    // 扩大
    MTTRZoomIn() {
      if (this.MTTRChartZoom < 1.5) {
        this.MTTRChartZoom += 0.1;
        this.updateMTTRChartSize();
      }
    },
    // 缩小
    MTTRZoomOut() {
      if (this.MTTRChartZoom > 0.7) {
        this.MTTRChartZoom -= 0.1;
        this.updateMTTRChartSize();
      }
    },
    // 刷新大小
    updateMTTRChartSize() {
      const chartDom = this.$refs.MTTRRef;
      chartDom.style.height = `${400 * this.MTTRChartZoom}px`;
      this.resizeChart();
    },
    // 查询
    async onMTTRSubmit() {
      if (this.typeMTTRCode) {
        this.confirmTypeMTTRLabels = this.typeMTTRLabels;
        await this.getMTTRChartOption(this.typeMTTRCode);
        let titleName = [...this.MTTRChartOption.legend.data];
        titleName.shift(); // 删除并返回第一个元素
        this.MTTRChartOption.title.text = titleName + "类设备MTTR趋势分析";
        this.refreshMTTRChart();
      }
    },
    // 确定设置MTTR标准
    onMTTRStandard() {
      if (this.MTTRStandard) {
        this.MTTRChartOption.series[0].markLine.data[0].yAxis =
          this.MTTRStandard;
        this.MTTRStandard = "";
        this.refreshMTTRChart();
      }
    },
    // 重置
    onMTTRReset() {
      this.MTTRStandard = "";
      this.typeMTTRCode = "";
      this.timeFrame = "";
    },
  },
};
</script>

<style scoped>
.card {
  margin-bottom: 10px;
}
/* 折线统计图 */
.echarts-container {
  width: 100%;
  height: 100%;
  padding: 10px;
}

/* 自定义tooltip样式 */
.el-tooltip__popper {
  max-width: 300px;
  min-height: 300px;
}
</style>  